import joblib
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import SearchParams
df = pd.read_excel('数据/特征筛选—血脉扩张-前20特征.xlsx')
print()
# df = df.drop(columns='id')
# 输出标签
label = pd.read_excel('数据/1-b-训练.xlsx')
label = label['是否发生血肿扩张']
print('label', label)
# 输入变量
variable = df
print('variable', variable)

label_column = '血肿扩张'


# ==========归一化============================
def df_mm(df):
    from sklearn.preprocessing import MinMaxScaler

    print('>>>>>>> 数据归一化')

    scaler = MinMaxScaler()
    df = scaler.fit_transform(df)

    return df


variable = df_mm(variable)

# ===============================================数据集分割===========================
train_x = variable[:100, :]
train_y = label[:100]
test_x = variable[100:, :]
test_y = label[100:]

print('训练集\n', train_x.shape, train_y.shape)  # (80, 108) (80,)
print('测试集\n', test_x.shape, test_y.shape)  # (20, 108) (20,)

# ===================XGboost===============
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV

# 网格搜索

# param_test = {"n_estimators":range(1,101,10)}
# model = GridSearchCV(estimator=RandomForestClassifier(),param_grid=param_test,scoring="roc_auc")
#
# model.fit(train_x, train_y)  # 训练模型

# {'n_estimators': 41}
# best:{'n_estimators': 21}
# param_test2 = {"max_features":range(1,11,1)}
# model = GridSearchCV(estimator=RandomForestClassifier(n_estimators=41),param_grid=param_test2,scoring="roc_auc").fit(train_x, train_y)


model = svm.SVC()
model.fit(train_x,train_y)
  # 训练模型
# # best{'max_features': 3}
# print(model.best_params_)
# print("best acc:%.4f"%model.best_score_)
# 训练XGBoost分类器
# n=1
# m=1
# model = RandomForestClassifier(n_estimators=51,max_features=2)
# K折交叉验证
# scores = cross_val_score(model, train_x, train_y)
# # 模型训练
# model.fit(train_x, train_y)  # 训练模型
# 保存模型
# joblib.dump(model, f'模型/预测模型-{label_column}-RF_优化_n{n}_m{m}.pkl')
# 加载模型
# model = joblib.load(f'模型/预测模型-血肿扩张-RF_优化_n{n}_m{m}.pkl')
# 预测
predict = model.predict(test_x)

# 转np
test_y = np.array(test_y)
predict = np.array(predict)

# ======i======================计算所有数据的概率===============================
probility = model.predict_proba(variable)
probility = pd.DataFrame(probility)
probility.to_excel('数据/血肿扩张概率-RF.xlsx')

# # 结果转化为0-1
# for i in range(predict.shape[0]):
#     if predict[i] < 0.5:
#         predict[i] = 0
#     else:
#         predict[i] = 1

# ==========计算准确率=============

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

real = test_y
accuracy_score = accuracy_score(real, predict)
precision_score = precision_score(real, predict)
recall_score = recall_score(real, predict)
f1_score = f1_score(real, predict)
accuracy_score_s=[]
precision_score_s=[]
print('准确率: %.4f' % accuracy_score)
print('精确率: %.4f' % precision_score)
print('召回率、: %.4f' % recall_score)
print('F1 score: %.4f' % f1_score)  # normalize=False 百分比

if precision_score>0.8:
    joblib.dump(model, f'模型/预测模型-{label_column}-RF_最优.pkl')

# ===========================================混淆矩阵=====================================
# https://blog.csdn.net/weixin_46039719/article/details/122897028

from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt


# ======================================绘制混淆矩阵=======================================
def plot_confusion_matrix(y_true, y_pred, classes,
                          normalize=False,
                          title=None,
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'

    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    # Only use the labels that appear in the data
    classes = classes[unique_labels(y_true, y_pred)]
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        # print("Normalized confusion matrix")
    else:
        pass
        # print('Confusion matrix, without normalization')

    # print(cm)

    fig, ax = plt.subplots()
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.figure.colorbar(im, ax=ax)
    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           # ... and label them with the respective list entries
           xticklabels=classes, yticklabels=classes,
           title=title,
           ylabel='True label',
           xlabel='Predicted label')

    ax.set_ylim(len(classes) - 0.5, -0.5)

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    plt.savefig('图像/混淆矩阵-RF', bbox_inches='tight', pad_inches=0.1, dpi=480)
    plt.show()

    return ax


class_names = np.array(["0", "1"])  # 按你的实际需要修改名称
plot_confusion_matrix(real, predict, classes=class_names, normalize=False)

# ROC曲线
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt

fpr, tpr, thersholds = roc_curve(real, predict)

roc_auc = auc(fpr, tpr)

plt.plot(fpr, tpr, 'k--', label='ROC (area = {0:.2f})'.format(roc_auc), lw=2)

plt.xlim([-0.05, 1.05])  # 设置x、y轴的上下限，以免和边缘重合，更好的观察图像的整体
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')  # 可以使用中文，但需要导入一些库即字体
plt.title('ROC Curve')
plt.legend(loc="lower right")
plt.show()

# Caco-2
'''
准确率: 0.8333
精确率: 0.3333
召回率、: 0.1111
F1 score: 0.1667
'''
